package com.sfl.api_backend.controller.files;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sfl.api_backend.constant.HttpCode;
import com.sfl.api_backend.entity.Scripts;
import com.sfl.api_backend.service.IScriptsService;
import com.sfl.api_backend.utils.Api.RestResult;
import com.sfl.api_backend.utils.RandomID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 脚本表 前端控制器
 * </p>
 *
 * @author szc
 * @since 2023-01-27
 */
@RestController
@RequestMapping("/files/scripts")
@Slf4j
public class ScriptsController {

    @Resource
    private IScriptsService scriptsService;

    @Value("${file.upload.path}")
    private String uploadPath;


    @PostMapping("/modify")
    @PreAuthorize("hasAuthority('User')")
    public RestResult modifly(@RequestBody Scripts scripts) {
        try {
            log.info("modifly scripts: {}", scripts);
            scriptsService.updateById(scripts);
            return RestResult.success();
        } catch (Exception e) {
            log.error("modifly scripts: {} error", scripts);
            System.out.println(e);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('User')")
    public RestResult list(@RequestBody Scripts vo) {
        try {
            log.info("list scripts: {}", vo.getUserId());
            Wrapper<Scripts> wrapper = new LambdaQueryWrapper<Scripts>().eq(Scripts::getUserId, vo.getUserId());
            return RestResult.success(scriptsService.list(wrapper));
        } catch (Exception e) {
            log.error("list scripts: {} error", vo.getUserId());
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/make")
    @PreAuthorize("hasAuthority('User')")
    public RestResult make(@RequestParam("files[]") List<MultipartFile> files, @RequestParam("names[]") List<String> names, @RequestParam("Ids[]") List<String> Ids) throws Exception {
        List<String> fileUrls = new ArrayList<>();
        log.info("调用了接口");

        File folder = new File(uploadPath + Ids.get(2) + "/scripts/");
        if (!folder.exists()) {
            boolean success = folder.mkdirs();
            if (!success) {
                return RestResult.error(500, "创建文件夹错误");
            }
        }

        for (int i = 0; i < files.size(); i++) {
            System.out.println(i);
            MultipartFile file = files.get(i);
            String name = names.get(i);
            if (!file.isEmpty()) {
                String scriptPath = uploadPath + Ids.get(2) + "/scripts/";

                File fileToSave = new File(scriptPath, name);
                try (OutputStream outputStream = new FileOutputStream(fileToSave)) {
                    outputStream.write(file.getBytes());

                    Scripts scripts = new Scripts();
                    scripts.setScriptId(RandomID.getRandomID());
                    scripts.setScriptName(Ids.get(0));
                    scripts.setUserId(Integer.valueOf(Ids.get(2)));
                    scripts.setScriptPath(scriptPath);
                    scripts.setTag(Integer.valueOf(Ids.get(1)));
                    scripts.setCreateTime(LocalDateTime.now());
                    scriptsService.save(scripts);
                } catch (Exception e) {
                    return RestResult.error(500, String.valueOf(e));

                }
            }
        }
        return RestResult.success();
    }

    @PostMapping("/delect")
    @PreAuthorize("hasAuthority('User')")
    public RestResult delect(@RequestBody List<Integer> scriptIds) {
        try {
            log.info("delect scripts: {}", scriptIds);
            List<Scripts> scripts = scriptsService.listByIds(scriptIds);

            // 删除文件
            for (Scripts script : scripts) {
                // remove file
                String path = script.getScriptPath();
                File file = new File(path);
                if (file.exists()) {
                    file.delete();
                }
            }

            scriptsService.removeBatchByIds(scriptIds);
            return RestResult.success();
        } catch (Exception e) {
            log.error("delect scripts: {} error", scriptIds);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

}
